const DailyLogModel = require("../model/dailyLogModel");

class DailyLogController {
  constructor() {
    this.dailyLogModel = new DailyLogModel();
  }

  // 正则：YYYY-MM-DD
  getDateRegex() {
    return /^\d{4}-\d{2}-\d{2}$/;
  }

  // 获取列表
  async getLogList(req, res) {
    try {
      const { startDate, endDate } = req.query;
      const dateRegex = this.getDateRegex();

      if (startDate && !dateRegex.test(startDate)) {
        return res.status(400).json({
          code: 1,
          msg: "查询参数 startDate 格式错误，应为 YYYY-MM-DD",
        });
      }
      if (endDate && !dateRegex.test(endDate)) {
        return res.status(400).json({
          code: 1,
          msg: "查询参数 endDate 格式错误，应为 YYYY-MM-DD",
        });
      }

      const result = await this.dailyLogModel.getLogList(req.query);
      res.json({
        code: 0,
        msg: "日志列表获取成功",
        data: result.list,
        pagination: result.pagination,
      });
    } catch (error) {
      console.error("获取日志列表失败:", error);
      res.status(500).json({
        code: 1,
        msg: "获取日志列表失败: " + error.message,
      });
    }
  }

  // 获取详情
  async getLogDetail(req, res) {
    try {
      const { id } = req.params;
      if (!id) {
        return res.status(400).json({
          code: 1,
          msg: "请提供日志ID",
        });
      }

      const log = await this.dailyLogModel.getLogById(id);
      if (!log) {
        return res.status(404).json({
          code: 1,
          msg: "日志不存在",
        });
      }

      res.json({
        code: 0,
        msg: "日志详情获取成功",
        data: log,
      });
    } catch (error) {
      console.error("获取日志详情失败:", error);
      res.status(500).json({
        code: 1,
        msg: "获取日志详情失败: " + error.message,
      });
    }
  }

  // 添加
  async createLog(req, res) {
    try {
      const logData = req.body;
      const { log_date, eat_time } = logData;
      const dateRegex = this.getDateRegex();

      if (!log_date || !dateRegex.test(log_date)) {
        return res.status(400).json({
          code: 1,
          msg: "日志日期（log_date）格式错误或缺失，应为 YYYY-MM-DD",
        });
      }
      if (eat_time === undefined || eat_time === null) {
        return res.status(400).json({
          code: 1,
          msg: "用餐时间（eat_time）缺失",
        });
      }

      const exists = await this.dailyLogModel.checkLogExists(
        log_date,
        eat_time
      );

      if (exists) {
        return res.status(409).json({
          // 409
          code: 1,
          msg: `日期 ${log_date} 的日志已存在，请勿重复添加`,
        });
      }

      const result = await this.dailyLogModel.createLog(logData);

      res.status(201).json({
        code: 0,
        msg: "日志添加成功",
        data: { id: result.id },
      });
    } catch (error) {
      console.error("添加日志失败:", error);

      const isValidationError =
        error.message.includes("必填项") ||
        error.message.includes("格式错误") ||
        error.message.includes("已存在记录");

      const statusCode = isValidationError ? 400 : 500;

      res.status(statusCode).json({
        code: 1,
        msg: "添加日志失败: " + error.message,
      });
    }
  }

  // 更新日志
  async updateLog(req, res) {
    try {
      const { id } = req.params;
      const logData = req.body;
      const { log_date, eat_time } = logData;
      const dateRegex = this.getDateRegex();

      if (!id) {
        return res.status(400).json({
          code: 1,
          msg: "请提供日志ID",
        });
      }

      const existingLog = await this.dailyLogModel.getLogById(id);
      if (!existingLog) {
        return res.status(404).json({
          code: 1,
          msg: "日志不存在",
        });
      }

      // 更新校验
      if (log_date && eat_time !== undefined && eat_time !== null) {
        if (!dateRegex.test(log_date)) {
          return res.status(400).json({
            code: 1,
            msg: "日志日期（log_date）格式错误，应为 YYYY-MM-DD",
          });
        }

        const exists = await this.dailyLogModel.checkLogExists(
          log_date,
          eat_time,
          id
        );

        if (exists) {
          return res.status(409).json({
            // 409
            code: 1,
            msg: `日期 ${log_date} 和用餐时间 ${eat_time} 的日志已存在于其他记录中，请勿重复更新`,
          });
        }
      } else if (log_date && (eat_time === undefined || eat_time === null)) {
        return res.status(400).json({
          code: 1,
          msg: "更新日志时，如果提供了log_date，则eat_time也为必填项",
        });
      } else if (!log_date && eat_time !== undefined && eat_time !== null) {
        return res.status(400).json({
          code: 1,
          msg: "更新日志时，如果提供了eat_time，则log_date也为必填项",
        });
      }

      const result = await this.dailyLogModel.updateLog(id, logData);

      res.json({
        code: 0,
        msg: "日志更新成功",
        data: { affectedRows: result.affectedRows },
      });
    } catch (error) {
      console.error("更新日志失败:", error);

      const isValidationError =
        error.message.includes("必填项") ||
        error.message.includes("格式错误") ||
        error.message.includes("已存在其他记录");

      const statusCode = isValidationError ? 400 : 500;

      res.status(statusCode).json({
        code: 1,
        msg: "更新日志失败: " + error.message,
      });
    }
  }

  // 删除日志
  async deleteLog(req, res) {
    try {
      const { id } = req.params;
      if (!id) {
        return res.status(400).json({
          code: 1,
          msg: "请提供日志ID",
        });
      }

      const existingLog = await this.dailyLogModel.getLogById(id);
      if (!existingLog) {
        return res.status(404).json({
          code: 1,
          msg: "日志不存在",
        });
      }

      const result = await this.dailyLogModel.deleteLog(id);
      res.json({
        code: 0,
        msg: "日志删除成功",
        data: { affectedRows: result.affectedRows },
      });
    } catch (error) {
      console.error("删除日志失败:", error);
      res.status(500).json({
        code: 1,
        msg: "删除日志失败: " + error.message,
      });
    }
  }

  // 获取核心统计数据
  async getCoreStats(req, res) {
    try {
      const { startDate, endDate, eat_time, log_week } = req.query;
      const dateRegex = this.getDateRegex();
      if (startDate && !dateRegex.test(startDate)) {
        return res.status(400).json({
          code: 1,
          msg: "开始日期格式错误，应为 YYYY-MM-DD",
          data: null,
        });
      }
      if (endDate && !dateRegex.test(endDate)) {
        return res.status(400).json({
          code: 1,
          msg: "结束日期格式错误，应为 YYYY-MM-DD",
          data: null,
        });
      }
      if (startDate && endDate && new Date(startDate) > new Date(endDate)) {
        return res.status(400).json({
          code: 1,
          msg: "开始日期不能晚于结束日期",
          data: null,
        });
      }
      const statsData = await this.dailyLogModel.getCoreStatistics({
        startDate,
        endDate,
        eat_time,
        log_week,
      });

      // 响应
      res.status(200).json({
        code: 0,
        msg: "统计数据获取成功",
        data: statsData,
      });
    } catch (error) {
      console.error("统计数据获取失败：", error);
      res.status(500).json({
        code: 1,
        msg: "服务器错误，统计数据获取失败: " + error.message,
        data: null,
      });
    }
  }
  // 根据指定日期获取当天的食材出库成本统计
  async getDailyCosts(req, res) {
    try {
      const { log_date } = req.params;
      const dateRegex = this.getDateRegex();

      if (!log_date || !dateRegex.test(log_date)) {
        return res.status(400).json({
          code: 1,
          msg: "查询日期（log_date）格式错误或缺失，应为 YYYY-MM-DD",
          data: null,
        });
      }

      const costs = await this.dailyLogModel.calculateDailyFoodCost(log_date);

      res.status(200).json({
        code: 0,
        msg: `${log_date} 食材成本获取成功`,
        data: {
          log_date: log_date,
          ...costs,
        },
      });
    } catch (error) {
      console.error("获取当日食材成本失败:", error);
      res.status(500).json({
        code: 1,
        msg: "服务器错误，获取当日食材成本失败: " + error.message,
        data: null,
      });
    }
  }
}

module.exports = DailyLogController;
